// import * as pdfjsLib from "../static/pdfjs/build/pdf.mjs";
// pdfjsLib.GlobalWorkerOptions.workerSrc =
// 	"/static/pdfjs/build/pdf.worker.mjs";
import * as pdfjsLib from "pdfjs-dist/legacy/build/pdf.min.mjs";
pdfjsLib.GlobalWorkerOptions.workerSrc =
	"/static/pdf.worker.min.mjs";
export const loadPdfFromData = (data, callback) => {
	pdfjsLib
		.getDocument({
			data: data
		})
		.promise.then(function(pdf) {
			const pageNumbers = Array.from(
				new Array(pdf.numPages),
				(val, index) => index + 1
			);
			return Promise.all(
				pageNumbers.map(function(num) {
					return pdf.getPage(num);
				})
			);
		})
		.then(function(pages) {
			// 渲染每一页到画布上
			let pdfHeight = 0
			const canvases = pages.map(function(page) {
				const viewport = page.getViewport({
					scale: 1
				});
				const canvas = document.createElement("canvas");
				canvas.width = viewport.width;
				canvas.height = viewport.height;
				if (pdfHeight <= 0) {
					pdfHeight = canvas.height
				}
				return page
					.render({
						canvasContext: canvas.getContext("2d"),
						viewport: viewport,
					})
					.promise.then(function() {
						return canvas;
					});
			});

			// 等待所有画布都准备好之后，将它们合并成一个大的画布
			return Promise.all(canvases).then(function(screenshots) {
				const combinedCanvas = document.createElement("canvas");
				combinedCanvas.width = Math.max(
					...screenshots.map((shot) => shot.width)
				);
				combinedCanvas.height = screenshots.reduce(
					(sum, shot) => sum + shot.height,
					0
				);
				const imgs = []
				screenshots.forEach((shot, index) => {
					const imgData = shot.toDataURL();
					if (imgData) {
						imgs.push({
							name: `img${index}`,
							url: imgData,
						});
					}

					if (imgs.length === screenshots.length) {
						callback && callback(imgs, combinedCanvas.width, pdfHeight)
					}

				});
				return imgs;
			});
		})
		.catch(function(reason) {
			console.error(`Failed to load PDF: ${reason}`);
		});
};